package com.spring.data.jpa.demo.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.spring.data.jpa.demo.core.entity.Team;
import com.spring.data.jpa.demo.core.service.TeamService;

@Controller
@RequestMapping("/team")
public class TeamController {

	@Autowired
	private TeamService teamService;

	@RequestMapping("/list")
	public String list(Model model) {

		List<Team> teams = teamService.getTeams();
		model.addAttribute("teams", teams);

		return "team/list";
	}

	@RequestMapping("/createOrUpdate")
	public String createOrUpdate(@ModelAttribute Team team) {

		if (team.getId() == null) {
			teamService.addTeam(team);
		} else {
			teamService.updateTeam(team);
		}
		return "redirect:./list";
	}

	@RequestMapping("/show/{id}")
	public String show(@PathVariable Integer id, Model model) {
		if (id != null) {
			model.addAttribute("team", teamService.getTeam(id));
		}
		return "team/show";
	}
	
	@RequestMapping("/show")
	public String show(Model model) {
		return show(null, model);
	}

	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable Integer id) {

		teamService.deleteTeam(id);

		return "redirect:../list";
	}

}
